﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using PersonaLibrary.Data;
using PersonaLibrary.View.EmploeeView;

namespace PersonaLibrary.Commands.EditCommands
{
	internal class LoadImageToEmployee : CommandBase
	{
		public override bool CanExecute(object parameter)
		{
			return parameter is int;
		}

		public override void Execute(object parameter)
		{
			LinqToDbDataContext context = new LinqToDbDataContext();
			Employee employee = context.Employees.FirstOrDefault(x => ((Employee)x).Id == (int)parameter);
			
			if(employee == null)
				throw new Exception(string.Format("Can't load employe with {0} id", parameter));

			OpenFileDialog dialog = new OpenFileDialog
			                        	{
											Filter = "Изображения |*.bmp;*.BMP;*.jpg;*.JPG;*.jpeg;*.JPEG"
			                        	};

			if (dialog.ShowDialog() == true)
			{
				Stream file = dialog.OpenFile();
				byte[] buffer = new byte[file.Length];
				file.Read(buffer, 0, (int) file.Length);
				employee.Foto = buffer;
				file.Dispose();
				context.SubmitChanges();
				context.Dispose();
				base.Execute(parameter);
			}
		}
	}
}
